//
//  MNDMineViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/4/28.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDMineViewController.h"
#import "MNDSign.h"
#import "MNDMineCellModel.h"
#import "MNDLoginUserModel.h"
#import "MNDUserModel.h"
#import "MNDRegisterViewController.h"
#import "MNDUserAutoTenderRank.h"
#import "MNDUserAssetModel.h"
#import "MNDUserMonthProfitModel.h"
#import "MNDMyProfileViewController.h"
#import "MNDDepositAlertViewController.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "MNDSettingViewController.h"
#import "MNDRechargeViewController.h"
#import "MNDWithdrawViewController.h"
#import "MNDRecordGroupViewController.h"
#import "MNDDiscountViewController.h"
#import "MNDAutoTenderViewController.h"
#import "MNDTenderTransferWMPageController.h"
#import "MNDInvestListViewController.h"
#import "MNDMessageViewController.h"
#import "MNDUserAssetViewController.h"
#import "MNDTransactionRecordViewController.h"
#import "SYRefreshControl.h"
#import "APIManager.h"
#import "UIImageView+JKAddition.h"
#import "UIButton+JKImagePosition.h"
#import "MNDLatestReturnWebViewController.h"
#import "MNDBackMoneyRootViewController.h"

#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDPersonalCenterViewController.h"

#import "MNDRiskAssessWebViewController.h"

#import <UMPush/UMessage.h>

#import "JhtMarqueeSDK.h"
#import "MNDOpenTermsAuthViewController.h"
#import "MNDMineTableViewCell.h"
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import "MNDBindWechatTableViewController.h"
#import <ShareSDKExtension/ShareSDK+Extension.h>

@interface MNDMineViewController () <UITableViewDataSource, UITableViewDelegate>

/*! 用户头像  */
@property (weak, nonatomic) IBOutlet UIButton *avatar;
/*! 用户昵称或手机号 */
@property (weak, nonatomic) IBOutlet UIButton *userNickname;
/*! 消息按钮 */
@property (weak, nonatomic) IBOutlet UIButton *btnMessage;
/*! 未登录情况下的遮罩层 */
@property (weak, nonatomic) IBOutlet UIView *barrierView;
/*! 账户余额的containerView */
@property (weak, nonatomic) IBOutlet UIView *balanceContainerView;
@property (weak, nonatomic) IBOutlet UIView *balanceContainerLeftView;
@property (weak, nonatomic) IBOutlet UIView *shadowView;

/*！ 账户余额 */
@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
/*！ 近30天收益 */
@property (weak, nonatomic) IBOutlet UILabel *monthlyIncomeLabel;
/*！ 总资产 */
@property (weak, nonatomic) IBOutlet UILabel *totalAssetsLabel;
@property (weak, nonatomic) IBOutlet UIButton *assetButton;

/*! 账单按钮 */
@property (weak, nonatomic) IBOutlet UIButton *billBtn;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *eyeButton;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSArray *cellArray;

/*! 优惠券数量 */
@property (nonatomic) NSInteger couponNum;

@property (nonatomic, strong) MNDUserModel *userModel;
@property (nonatomic, strong) MNDUserAutoTenderRank *userAutoTenderInfo;
@property (nonatomic, strong) MNDUserAssetModel *userAssetInfo;
@property (nonatomic, strong) MNDUserMonthProfitModel *userMonthProfitInfo;

@property (weak, nonatomic) MNDDepositAlertViewController *alertVC;

@property (strong, nonatomic) NSString *networkId;

@property (weak, nonatomic) IBOutlet UIView *assetTipsView;
@property (weak, nonatomic) IBOutlet UIView *recordTipsView;
@property (weak, nonatomic) IBOutlet UIView *userTipsView;

@property (nonatomic) BOOL stopAnimation;

/**
 是否是下拉刷新触发的
 */
@property (nonatomic) BOOL isPullDown;

/**
 回款明细数据请求ID
 */
@property(nonatomic, strong) NSString *monthProfitRequestId;

/**
 自动投标数据请求ID
 */
@property(nonatomic, strong) NSString *autoTenderRequestId;

/**
 优惠券数据请求ID
 */
@property(nonatomic, strong) NSString *couponRequestId;

/**
 刷新余额数据请求ID
 */
@property(nonatomic, strong) NSString *refreshRequestId;

/**
 存管状态的请求ID
 */
@property (nonatomic, strong) NSString *depositInfoRequestId;

/**
 刷新余额按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *refreshBalanceButton;

/**
 未读消息数
 */
@property (weak, nonatomic) IBOutlet UILabel *unreadMessageCountLabel;

@property (weak, nonatomic) IBOutlet UIButton *latestIncomeButton;

/**
 用户存管手机号
 */
@property (nonatomic, copy) NSString *userPhone;

/**
 是否点击了提现
 */
@property (nonatomic, assign) BOOL isClickWithdraw;

/**
 水平滚动跑马灯
 */
@property (nonatomic, strong) JhtHorizontalMarquee *horizontalMarquee;

/**
 存管信息
 */
@property (nonatomic, strong) ResponseModel *depositResponse;

/**
 未开通存管时的滚动条
 */
@property (nonatomic, strong) UIView *depositHeaderView;

/**
 是否已显示开通存管账户的弹框
 */
@property (nonatomic, assign) BOOL isAlertOpenAccount;

/**
 是否已显示设置交易密码的弹框
 */
@property (nonatomic, assign) BOOL isAlertPasswordSet;

/**
 是否已显示缴费授权的弹框
 */
@property (nonatomic, assign) BOOL isAlertPayment;

/**
 是否已显示自动投标授权的弹框
 */
@property (nonatomic, assign) BOOL isAlertTender;

/**
 是否已显示自动债转的弹框
 */
@property (nonatomic, assign) BOOL isAlertTransfer;

/**
 是否已显示风险评测的弹框
 */
@property (nonatomic, assign) BOOL isAlertRiskAssessment;

/**
 是否已显示缴费授权过期的弹框
 */
@property (nonatomic, assign) BOOL isAlertPaymentExpired;

/**
 是否已显示自动投标已过期的弹框
 */
@property (nonatomic, assign) BOOL isAlertTenderExpired;

/**
 是否已显示债转授权已过期的弹框
 */
@property (nonatomic, assign) BOOL isAlertTransferExpired;

@property (nonatomic, strong) NSString *evaluationUrl;

@property (weak, nonatomic) IBOutlet UIView *topView;


@end

@implementation MNDMineViewController

#pragma mark - Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.naviBarTranslucent = YES;
    self.makeFullScreen = YES;
    
    if (@available(iOS 11, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self configViewLayer];
    
    [self.billBtn jk_setImagePosition: LXMImagePositionRight spacing:0];
//    self.isOpenDeposit = NO; //默认未开通存管
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toFinanceListVC) name:@"to_finance_list" object:nil];
    
    if ([MNDLoginUserModel isUserLogin]) {
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        //设置消息推送别名
        [UMessage setAlias: user.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
            if (error) {
                NSLog(@"设置别名失败: %@", error);
            } else {
                NSLog(@"设置别名成功: %@", responseObj);
            }
        }];
    }
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToDiscountVC:) name:kGoToDiscountVC object:nil];
    //兼容旧版本
    BOOL alert = [UserDefaultsTool boolForKey:kOpenDepositAlert];
    if (!alert) {
        [UserDefaultsTool saveBool:NO forKey:kOpenDepositAlert];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    if (self.horizontalMarquee) {
        [self.horizontalMarquee marqueeOfSettingWithState:MarqueeStart_H];
    }
    
    self.depositInfoRequestId = nil;
    self.couponRequestId = nil;
    self.refreshRequestId = nil;
    self.autoTenderRequestId = nil;
    self.monthProfitRequestId = nil;
    self.networkId = nil;
    self.isClickWithdraw = NO;
    
    if ([MNDLoginUserModel isUserLogin]) {
        self.topView.backgroundColor = [UIColor clearColor];
        [self.barrierView setHidden:YES];
        
        WeakSelf(self);

        [SYRefreshControl configGifMJRefresh:self.tableView refreshType:MJRefreshSupportRefresh beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
            weakself.isPullDown = YES;
            [weakself loadInfos];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself loadCellDatas];
                [weakself loadDepositInfo:YES];
                [weakself loadInfos];
                
            });
        } loadMoreBlock:nil];

        [self loadUserPhone];
        [self loadDepositInfo:YES];
        
        [self loadCellDatas];
        [self loadInfos];
        
        if (self.userModel.comeInIsUpdate.integerValue == 1) {
            self.stopAnimation = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self refreshBalanceAction:self.refreshBalanceButton];
            });
        }
    } else {
        self.topView.backgroundColor = [UIColor whiteColor];
        self.unreadMessageCountLabel.text = @"";
        [self.unreadMessageCountLabel setHidden:YES];
        self.tableView.mj_header = nil;
        self.depositResponse = nil;
        
        self.isAlertOpenAccount = NO;
        self.isAlertPasswordSet = NO;
        self.isAlertPayment = NO;
        self.isAlertTender = NO;
        self.isAlertTransfer = NO;
        self.isAlertRiskAssessment = NO;
        self.isAlertPaymentExpired = NO;
        self.isAlertTenderExpired = NO;
        self.isAlertTransferExpired = NO;
        
        [self.tableView reloadData];
    }
    [self configResponseContents];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self cancelRequests];
    
    if (self.horizontalMarquee) {
        [self.horizontalMarquee marqueeOfSettingWithState:MarqueeShutDown_H];
    }
}

- (void)cancelRequests {
    if (self.monthProfitRequestId) {
        [XMCenter cancelRequest:self.monthProfitRequestId];
    }
    if (self.autoTenderRequestId) {
        [XMCenter cancelRequest:self.autoTenderRequestId];
    }
    if (self.couponRequestId) {
        [XMCenter cancelRequest:self.couponRequestId];
    }
    if (self.refreshRequestId) {
        [XMCenter cancelRequest:self.refreshRequestId];
    }
    
    if (self.depositInfoRequestId) {
        [XMCenter cancelRequest:self.depositInfoRequestId];
    }
    
    if (self.networkId) {
        [XMCenter cancelRequest:self.networkId];
    }
}

//原始状态
- (void)configInitialContents {
    [self.barrierView setHidden:NO];
    [self.avatar setImage:[UIImage imageNamed:@"user_center_avatar_color"] forState:UIControlStateNormal];
    [self.userNickname setTitle:@"" forState:UIControlStateNormal];
    [self.btnMessage setImage:[UIImage imageNamed:@"user_center_message_icon"] forState:UIControlStateNormal];
    self.totalAssetsLabel.text = @"0.00";
    self.monthlyIncomeLabel.text = @"0.00";
    self.balanceLabel.text = @"0.00";
    self.userModel = [MNDUserModel new];
    self.userAutoTenderInfo = [MNDUserAutoTenderRank new];
    self.userAssetInfo = [MNDUserAssetModel new];
    self.userMonthProfitInfo = [MNDUserMonthProfitModel new];
    self.couponNum = 0;
    
    self.cellArray = @[
                       @[@{@"title": @"出借记录", @"subtitle": @"", @"icon": @"user_center_record_icon"},
                         @{@"title": @"回款明细", @"subtitle": @"", @"icon": @"user_center_return_icon"},
                         @{@"title": @"账户记录", @"subtitle": @"", @"icon": @"user_center_bill_icon"}],
                       @[@{@"title": @"自动投标", @"subtitle": @"", @"icon": @"user_center_auto_tender_icon"},
                         @{@"title": @"债权转让", @"subtitle": @"", @"icon": @"user_center_creditor_icon"}],
                       
                       @[@{@"title": @"我的邀请", @"subtitle": @"",  @"icon": @"user_center_invite_icon"},
                         @{@"title": @"我的卡券",   @"subtitle": @"", @"icon": @"user_center_coupon_icon"}]
                       ];
    [self.tableView reloadData];
}

//去投资列表
- (void)toFinanceListVC {
    [self.tabBarController setSelectedIndex:1];
}

//设置一些view的边框和圆角阴影等
- (void)configViewLayer {
    self.registerBtn.layer.cornerRadius = 3.0;
    self.registerBtn.layer.borderWidth = 1.0;
    self.registerBtn.layer.borderColor = kColorOrange.CGColor;
    
//    self.balanceContainerView.layer.cornerRadius = 3.0;
//    self.balanceContainerView.layer.shadowOpacity = 0.4;
//    self.balanceContainerView.layer.shadowOffset = CGSizeMake(3.0, 3.0);
//    self.balanceContainerView.layer.shadowRadius = 3.0;
//    self.balanceContainerView.layer.shadowColor = kColorLightGray.CGColor;
    
    self.shadowView.layer.cornerRadius = 3.0;
    self.shadowView.layer.shadowOpacity = 0.4;
    self.shadowView.layer.shadowOffset = CGSizeMake(3.0, -3.0);
    self.shadowView.layer.shadowRadius = 3.0;
    self.shadowView.layer.shadowColor = kColorLightGray.CGColor;
}

/**
 刷新余额

 @param sender
 */
- (IBAction)refreshBalanceAction:(UIButton *)sender {
    self.stopAnimation = NO;
    [self startRotation:sender];

    [self updateAssetWithUrl:self.userModel.updateAccountUrl];
}

- (void)startRotation:(UIButton *)button {
    
    [UIView animateWithDuration:1/3.0 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        button.transform = CGAffineTransformRotate(button.transform, -M_PI_2);
    } completion:^(BOOL finished) {
        if (!self.stopAnimation) {
            [self startRotation:button];
        }
    }];
}

#pragma mark - Network

/**
 获取用户基本信息，资产，账户余额等信息
 */
- (void)loadInfos {
    
    WeakSelf(self);
    
    self.networkId =
    [XMCenter sendBatchRequest:^(XMBatchRequest * _Nonnull batchRequest) {
        
        //用户基本信息
        XMRequest *userBaseInfoReq = [XMRequest request];
        userBaseInfoReq.api = API_USER_BASE_INFO;
        userBaseInfoReq.parameters = [MNDSign signedParam];
        userBaseInfoReq.httpMethod = kXMHTTPMethodGET;
        userBaseInfoReq.responseSerializerType = kXMResponseSerializerJSON;
        
        [NSThread sleepForTimeInterval:0.01];
        //用户资产明细
        XMRequest *assetReq = [XMRequest request];
        assetReq.api = API_USER_ASSET_LIST;
        assetReq.parameters = [MNDSign signedParam];
        assetReq.httpMethod = kXMHTTPMethodGET;
        assetReq.responseSerializerType = kXMResponseSerializerJSON;
        
        [APIManager addGeneralHeaders];
        
        [batchRequest.requestArray addObjectsFromArray:@[userBaseInfoReq, assetReq]];
        
    } onSuccess:^(NSArray * _Nonnull responseObjects) {
        for (NSInteger i = 0; i < responseObjects.count; i++) {
            ResponseModel *response = [ResponseModel mj_objectWithKeyValues:responseObjects[i]];
            
            NSLog(@"response: %@", responseObjects[i]);
            
            if (response.status == ResponseFailure) {
                NSDictionary *dict = response.msg;
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                return;
            }
            switch (i) {
                case 0:  //用户基本信息
                {
                    weakself.userModel = [MNDUserModel mj_objectWithKeyValues:response.data];
                    weakself.evaluationUrl = weakself.userModel.evaluationUrl;
                }
                    break;

                case 1:  //用户资产明细
                {
                    weakself.userAssetInfo = [MNDUserAssetModel mj_objectWithKeyValues:response.data];
                }
                    break;

                default:
                    break;
            }
        }
        if (weakself.userModel.isUpdateAccount.integerValue == 1 && weakself.isPullDown) {
            weakself.stopAnimation = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself refreshBalanceAction:weakself.refreshBalanceButton];
            });
        }
        [weakself configResponseContents];
        
    } onFailure:^(NSArray * _Nonnull errors) {
        NSLog(@"errors: %@", errors);
        weakself.isPullDown = NO;
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:NO];
        for (id error in errors) {
            if ([error isKindOfClass:[NSError class]]) {
                NSError *err = error;
                if (err.code == -999) {
                    return;
                }
                [NetworkProgressHUD showHudNetworkError:error];
                return;
            }
        }
    } onFinished:^(NSArray * _Nullable responseObjects, NSArray * _Nullable errors) {
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:NO];
        weakself.isPullDown = NO;
        if (errors && errors.count > 0) {
            return;
        }
    }];
}

/**
 获取当前投资记录，回款，自动投标排名，赠利券等数据
 */
- (void)loadCellDatas {
    WeakSelf(self);
    //用户回款明细
    self.monthProfitRequestId = [APIManager sendRequestWithPath:API_MONTH_PROFIT parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userMonthProfitInfo = [MNDUserMonthProfitModel mj_objectWithKeyValues:responseModel.data];
            [weakself configResponseContents];
        }
        NSLog(@"month profit: %@", responseModel.data);
    } onFailure:^(NSError *error) {
        
    }];
    //用户自动投标排名
    self.autoTenderRequestId = [APIManager sendRequestWithPath:API_FORECAST_TENDER_RANKING parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userAutoTenderInfo = [MNDUserAutoTenderRank mj_objectWithKeyValues:responseModel.data];
            [weakself configResponseContents];
        }
        NSLog(@"tender_ranking: %@", responseModel.data);
    } onFailure:^(NSError *error) {
        
    }];
    //用户优惠券信息
    NSDictionary *couponParams = [MNDSign signedParamWithDict:@{@"coupon_status": @"1"}];
    self.couponRequestId = [APIManager sendRequestWithPath:API_DISCOUNT_LIST parameters:couponParams method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.couponNum = [responseModel.data[@"sum"] integerValue];
            [weakself configResponseContents];
            NSLog(@"coupon_list_data: %@", responseModel.data);
        }
    } onFailure:^(NSError *error) {
        
    }];
}

- (void)updateAssetWithUrl:(NSString *)url {
    WeakSelf(self);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *requestUrl = [url stringByAppendingFormat:@"/%@", API_UPDATE_ASSET];
       self.refreshRequestId = [APIManager sendRequestWithURL:requestUrl parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
            NSLog(@"response: %@", responseModel.data);
            weakself.stopAnimation = YES;
           if (responseModel.status == ResponseSuccess) {
               weakself.userAssetInfo.userAmountAssets = responseModel.data[@"user_amount_assets"];
               
               weakself.userAssetInfo.userAmountAvailable = responseModel.data[@"user_amount_available"];
               [weakself configResponseContents];
               
               [[NSNotificationCenter defaultCenter] postNotificationName:@"update_user_balance" object:responseModel];
           }
        } onFailure:^(NSError *error) {
            weakself.stopAnimation = YES;
        }];
    });
}

/**
 获取存管手机号
 */
- (void)loadUserPhone {
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userPhone = responseModel.data;
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadDepositInfo:(BOOL)autoAlert {
    
    WeakSelf(self);
    self.depositInfoRequestId =
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                if (!autoAlert) {
                    [NetworkProgressHUD hideHud];
                }
                
                NSString *signStr = responseModel.msg[@"sign"];
                
                if ([signStr isEqualToString:kRiskEvaluation]) {
                    weakself.evaluationUrl = responseModel.data[@"risk_url"];
                }
                
                if (autoAlert) {
                    [weakself configDepositWithModel:responseModel];
                    
                } else {
                    [weakself showOpenDepositAlert:responseModel];
                }
                weakself.depositResponse = responseModel;
            } else {
                weakself.depositResponse = nil;
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
            if (weakself.isClickWithdraw) {
                weakself.isClickWithdraw = NO;
                [weakself toWithdrawViewController];
            }
            weakself.depositResponse = nil;
            if (!autoAlert) {
                [NetworkProgressHUD hideHud];
            }
        }
        [weakself.tableView reloadData];
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configDepositWithModel:(ResponseModel *)response {
    
    NSString *signStr = response.msg[@"sign"];
    //未开通存管
    if ([signStr isEqualToString:kOpenAccount] && !self.isAlertOpenAccount) {
        
        [self showOpenDepositAlert:response];

        self.isAlertOpenAccount = YES;
        return;
    }
    
    //未设置交易密码
    if ([signStr isEqualToString:kSetPassword] && !self.isAlertPasswordSet) {
        
        [self showOpenDepositAlert:response];

        self.isAlertPasswordSet = YES;
        return;
    }
    
    //未签约缴费授权
    if ([signStr isEqualToString:kSignPayment] && !self.isAlertPayment) {
        
        [self showOpenDepositAlert:response];

        self.isAlertPayment = YES;
        return;
    }
    
    //未签约自动投标
    if ([signStr isEqualToString:kSignAutoTender] && !self.isAlertTender) {
        
        [self showOpenDepositAlert:response];

        self.isAlertTender = YES;
        return;
    }
    
    //未签约自动债转
    if ([signStr isEqualToString:kSignAutoTransfer]  && !self.isAlertTransfer) {
        
        [self showOpenDepositAlert:response];

        self.isAlertTransfer = YES;
        return;
    }
    
//    //风险等级未评测
//    if ([signStr isEqualToString:kRiskEvaluation] && !self.isAlertRiskAssessment) {
//
//        [self showRiskAlertView];
//
//        self.isAlertRiskAssessment = YES;
//        return;
//    }
    
    //缴费授权已过期
    if ([signStr isEqualToString:kExpiredSignPayment] && !self.isAlertPaymentExpired) {
        
        [self showOpenDepositAlert:response];

        self.isAlertPaymentExpired = YES;
        return;
    }
    
    //自动投标授权已过期
    if ([signStr isEqualToString:kExpiredAutotender] && !self.isAlertTenderExpired) {
        
        [self showOpenDepositAlert:response];

        self.isAlertTenderExpired = YES;
        return;
    }
}

- (BOOL)isCurrentViewControllerVisable {
    return (self.isViewLoaded && self.view.window);
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];

    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    self.alertVC = alertVC;
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
    
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
    
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)showOpenDepositAlert:(ResponseModel *)response {
    
    //如果当前页面正在显示，才会弹出提示框
    if (![self isCurrentViewControllerVisable]) {
        return;
    }
    if (![MNDLoginUserModel isUserLogin]) {
        return;
    }
    
    NSString *signStr = response.msg[@"sign"];
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    //进入提现
    if (self.isClickWithdraw) {
        self.isClickWithdraw = NO;
        if (![signStr isEqualToString:kSetPassword]) {
            
            [self toWithdrawViewController];
            return;
        }
    }
    
    __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
    __weak UIView *alertView = alertVC.view;
    [KeyWindow addSubview:alertView];
    [self.tabBarController addChildViewController:alertVC];
    
    WeakSelf(self);
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
    
        [weakself toOpenDepositoryWithModel:response];
    
    } forControlEvents:UIControlEventTouchUpInside];
    
    alertVC.alertMessage = response.msg[@"error"];
    alertVC.alertType = response.msg[@"sign"];
}

/**
 进入提现页面
 */
- (void)toWithdrawViewController {
    self.isClickWithdraw = NO;
    [self performSegueWithIdentifier:[MNDWithdrawViewController description] sender:nil];
}

- (MNDOpenDepositoryViewController *)extracted {
    MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
    return realVC;
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController * realVC = [self extracted];
        realVC.fromNaviIndex = index;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment] || [signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender] || [signStr isEqualToString:kSignAutoTransfer]) {
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = index;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
    }
    
    //绑定微信
    if ([signStr isEqualToString:kBindWechat]) {
        [self bindWechat];
    }
    
//    //设置缴费授权
//    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment] ) {
//        
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = index;
//        
//        [self.navigationController pushViewController:paymentVC animated:YES];
//        
//        return;
//    }
//    //设置自动投标
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//        
//        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//        tenderVC.isResign = YES;
//        if (self.userPhone.length > 0) {
//            tenderVC.fromNaviIndex = index;
//            tenderVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
//    //设置自动债转
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//        
//        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//        if (self.userPhone.length > 0) {
//            transferVC.fromNaviIndex = index;
//            transferVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
    //风险测评
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self toRiskViewController];
        return;
    }
}

/**
 风险测评
 */
- (void)toRiskViewController {
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    
    MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
    riskVC.webViewUrl = self.evaluationUrl;
    riskVC.indexOfViewController = index;
    riskVC.title = @"风险测评";
    riskVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:riskVC animated:YES];
}

- (void)showRiskAlertView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self toRiskViewController];
        
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

#pragma mark - 网络请求返回数据处理

/*! 统一配置返回的数据 */
- (void)configResponseContents {
    if (![MNDLoginUserModel isUserLogin]) {
        [self configInitialContents];
        return;
    }
    //昵称
    [self.userNickname setTitle:self.userModel.userName forState:UIControlStateNormal];
    //消息
    [self.unreadMessageCountLabel setHidden:self.userModel.userUnreadinfoNum.integerValue <= 0];
    
    if (self.userModel.userUnreadinfoNum.integerValue > 9) {
        self.unreadMessageCountLabel.text = [NSString stringWithFormat:@"%@  ", self.userModel.userUnreadinfoNum];
    } else {
        self.unreadMessageCountLabel.text = self.userModel.userUnreadinfoNum;
    }
    
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:self.userModel.userPhoto]
                           forState:UIControlStateNormal
                   placeholderImage:[UIImage imageNamed:@"user_center_avatar_color"]];
    
    self.totalAssetsLabel.text = self.userAssetInfo.userAmountAssets.doubleValue > 0 ? self.userAssetInfo.userAmountAssets : @"0.00";

    self.balanceLabel.text = self.userAssetInfo.userAmountAvailable.doubleValue > 0 ? self.userAssetInfo.userAmountAvailable : @"0.00";

    self.monthlyIncomeLabel.text = self.userAssetInfo.userInterestAmount.doubleValue > 0 ? self.userAssetInfo.userInterestAmount : @"0.00";
    
    NSString *investments = self.userAssetInfo.userCurrentTenderAmount;
    investments = investments.doubleValue > 0.0 ? [NSString stringWithFormat:@"出借金额%@", investments] : @"出借金额0.00";
    
    NSString *returnAmount = self.userAssetInfo.userWaitAmount;
    returnAmount = returnAmount.doubleValue > 0.0 ? [NSString stringWithFormat:@"待收总额%@", returnAmount] : @"待收总额0.00";
    
    if (self.eyeButton.isSelected && [MNDLoginUserModel isUserLogin]) {
        self.totalAssetsLabel.text = @"******";
        
        self.balanceLabel.text = @"******";
        
        self.monthlyIncomeLabel.text = @"******";
        investments = @"出借金额****";
        returnAmount = @"待收总额****";
    }
    
    NSString *tenderRank = self.userAutoTenderInfo.autoTenderRank;
    tenderRank = tenderRank.integerValue > 0 ? [NSString stringWithFormat:@"排名%@位", tenderRank] : @"";
    
    NSString *couponNum = self.couponNum > 0 ? [NSString stringWithFormat:@"%zd张", self.couponNum] : @"";
    
    self.cellArray = @[
                       @[@{@"title": @"出借记录", @"subtitle": investments,     @"icon": @"user_center_record_icon"},
                         @{@"title": @"回款明细", @"subtitle": returnAmount,    @"icon": @"user_center_return_icon"},
                         @{@"title": @"账户记录", @"subtitle": @"",    @"icon": @"user_center_bill_icon"}],
                       @[@{@"title": @"自动投标", @"subtitle": tenderRank,      @"icon": @"user_center_auto_tender_icon"},
                         @{@"title": @"债权转让", @"subtitle": @"",             @"icon": @"user_center_creditor_icon"}],
                       @[@{@"title": @"我的邀请", @"subtitle": @"",             @"icon": @"user_center_invite_icon"},
                         @{@"title": @"我的卡券", @"subtitle": couponNum,       @"icon": @"user_center_coupon_icon"}]
                       ];
    [self.tableView reloadData];
    
    if (self.alertVC) {
        return;
    }
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.cellArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = self.cellArray[section];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.depositResponse && section == 0) {
        NSString *signStr = self.depositResponse.msg[@"sign"];
        if (![ShareSDK isClientInstalled:SSDKPlatformTypeWechat] && [signStr isEqualToString:kBindWechat]) {//未安装微信且未绑定微信不显示头部
            return 10;
        }
        return 35.0;
    } else {
        return 10.0;
    }
    return 10.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.depositResponse && section == 0) {
        NSString *signStr = self.depositResponse.msg[@"sign"];
        if (![ShareSDK isClientInstalled:SSDKPlatformTypeWechat] && [signStr isEqualToString:kBindWechat]) {//未安装微信且未绑定微信不显示头部
            return nil;
        }
        return self.depositHeaderView;
    } else {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
    
    if (self.depositResponse) {
        self.horizontalMarquee.text = [NSString stringWithFormat:@"%@     ", self.depositResponse.msg[@"error"]];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    static NSString *const cellIdentifier = @"cell1";
//    static NSString *const cellIdentifier2 = @"cell2";
//
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//
//    if (!cell) {
//
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier2];
//    }
    MNDMineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDMineTableViewCell"];
    
    NSDictionary *dict = self.cellArray[indexPath.section][indexPath.row];
    
    cell.titleLabel.text = dict[@"title"];
    cell.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:16.0];
    cell.titleLabel.textColor = kColorBlack;
    cell.subtitleLabel.text = dict[@"subtitle"];
    cell.subtitleLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:12.0];
    cell.subtitleLabel.textColor = kColorLightGray;
    cell.iconImgView.image = [UIImage imageNamed:dict[@"icon"]];
    if (indexPath.section == 2 && indexPath.row == 0) {
        cell.statusImgView.hidden = NO;
    }else {
        cell.statusImgView.hidden = YES;
    }
//    UIImageView *accesoryView = [UIImageView jk_imageViewWithImageNamed:@"user_center_cell_arrow"];
//    cell.accessoryView = accesoryView;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (![MNDLoginUserModel isUserLogin]) {
        [self goLoginAction:nil];
        
        return;
    }
    
    if (indexPath.section == 0) {
        //投资记录
        if (indexPath.row == 0) {
            [self performSegueWithIdentifier:[MNDRecordGroupViewController description] sender:nil];
        }
        //回款明细
        if (indexPath.row == 1) {
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:[MNDBackMoneyRootViewController description] bundle:nil];
            
            MNDBackMoneyRootViewController *returnVC = [storyboard instantiateViewControllerWithIdentifier:[MNDBackMoneyRootViewController description]];
            returnVC.isUnReturn = YES;
            
            [self.navigationController pushViewController:returnVC animated:YES];
        }
        if (indexPath.row == 2) {
            [self performSegueWithIdentifier:[MNDTransactionRecordViewController description] sender:nil];
        }
    }
    
    if (indexPath.section == 1) {
        //自动投标
        if (indexPath.row == 0) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
            MNDAutoTenderViewController *autotenderVC = [storyboard instantiateViewControllerWithIdentifier: [MNDAutoTenderViewController description]];
            
            autotenderVC.autoTenderStatus = self.userModel.userIsaddAutotender;
            [self.navigationController pushViewController:autotenderVC animated:YES];
        }
        //债权转让
        if (indexPath.row == 1) {
            
            MNDTenderTransferWMPageController *transferVC = [[MNDTenderTransferWMPageController alloc] init];
            transferVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:transferVC animated:YES];
        }
    }
    
    if (indexPath.section == 2) {
        //我的邀请
        if (indexPath.row == 0) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
            MNDInvestListViewController *investListVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDInvestListViewController"];
            [self.navigationController pushViewController:investListVC animated:YES];
        }
        //赠利券
        if (indexPath.row == 1) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
            MNDDiscountViewController *couponVC = [storyboard instantiateViewControllerWithIdentifier: [MNDDiscountViewController description]];
            [self.navigationController pushViewController:couponVC animated:YES];
        }

        
//        if (indexPath.row == 2) {
//            [self goSettingAction:nil];
//        }
    }
    
}

#pragma mark - Action

- (IBAction)goUserProfileAction:(id)sender {
    
    if ([MNDLoginUserModel isUserLogin]) {
//        [self performSegueWithIdentifier:[MNDMyProfileViewController description] sender:nil];
         MNDPersonalCenterViewController *userCenterVC = [UIStoryboard viewControllerWithIdentifier:@"MNDPersonalCenterViewController"];
        userCenterVC.user = self.userModel;
        [self.navigationController pushViewController:userCenterVC animated:YES];
        
    } else {
        [self goLoginAction:nil];
    }
}

/*！ 设置 */
- (IBAction)goSettingAction:(id)sender {
    if ([MNDLoginUserModel isUserLogin]) {
        [self performSegueWithIdentifier:[MNDSettingViewController description] sender:nil];
    } else {
        [self goLoginAction:nil];
    }
}

/*！ 查看消息 */
- (IBAction)readMsgAction:(id)sender {
    
    if ([MNDLoginUserModel isUserLogin]) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
        MNDMessageViewController *msgVC = [storyboard instantiateViewControllerWithIdentifier:[MNDMessageViewController description]];
        msgVC.isShowAcountMsg = YES;
        if (self.userModel.userUnreadinfoNum.integerValue >= 0) {
            msgVC.shouldReadAllMsg = YES;
        }
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:msgVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    } else {
        [self goLoginAction:nil];
    }
}

/*！ 登录 */
- (IBAction)goLoginAction:(id)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

/*！ 注册 */
- (IBAction)goRegisterAction:(id)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    MNDRegisterViewController *registerVC = [storyboard instantiateViewControllerWithIdentifier:[MNDRegisterViewController description]];
    [naviVC setViewControllers:@[registerVC] animated:YES];
    registerVC.isNaviRootVC = YES;
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

/*！  资产分析 */
- (IBAction)goAssetAction:(id)sender {
    
    [self performSegueWithIdentifier:[MNDUserAssetViewController description] sender:nil];
}

- (IBAction)assetAtion:(UIButton *)sender {
    [self performSegueWithIdentifier:[MNDUserAssetViewController description] sender:nil];
}

/*！  查看账单 */
- (IBAction)auditAction:(id)sender {
    [self performSegueWithIdentifier:[MNDTransactionRecordViewController description] sender:nil];
}

/*！ 充值 */
- (IBAction)rechargeAction:(id)sender {
    
    [self performSegueWithIdentifier:[MNDRechargeViewController description] sender:nil];
}

/*！ 提现 */
- (IBAction)withdrawAction:(id)sender {
    
    [NetworkProgressHUD showHud];
    self.isClickWithdraw = YES;
    [self loadDepositInfo:NO];
}

/*！ 赠利券  */
- (void)goToDiscountVC:(NSNotification *)notification {
    if (![MNDLoginUserModel isUserLogin]) {
        [self goLoginAction:nil];
        
        return;
    }
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    MNDDiscountViewController *couponVC = [storyboard instantiateViewControllerWithIdentifier: [MNDDiscountViewController description]];
    [self.navigationController pushViewController:couponVC animated:YES];
}

/*！ 显示或隐藏总资产金额 */
- (IBAction)showOrHideAssetesAction:(id)sender {
    
    UIButton *btn = sender;
    btn.selected = !btn.isSelected;
    
    [self configResponseContents];
}

/**
 （最近30天收益列表）改为已赚收益跳转到资产统计

 @param sender
 */
- (IBAction)latestIncomeAction:(UIButton *)sender {
    [self performSegueWithIdentifier:[MNDUserAssetViewController description] sender:nil];
//    [self loadEncodeUserCode];
}

- (void)loadEncodeUserCode {
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"user_code": user.user_code}];
    [APIManager sendRequestWithPath:API_ENCODE_USERCODE parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:[MNDLatestReturnWebViewController description] bundle:nil];
                MNDLatestReturnWebViewController *returnVC = [storyboard instantiateViewControllerWithIdentifier:[MNDLatestReturnWebViewController description]];
                returnVC.url = weakself.userMonthProfitInfo.return_income_30day_url;
                returnVC.encodeUserCode = responseModel.data[@"user_code"];
                [weakself.navigationController pushViewController:returnVC animated:YES];
            });
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)depositButtonAction:(UIButton *)sender {
    [self toOpenDepositoryWithModel:self.depositResponse];
}



#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:[MNDMyProfileViewController description]]) {
        MNDMyProfileViewController *myProfileVC = segue.destinationViewController;
        myProfileVC.user = self.userModel;
       
        
    }
}

#pragma mark - Getter Method

- (MNDUserModel *)userModel {
    if (!_userModel) {
        _userModel = [[MNDUserModel alloc] init];
    }
    
    return _userModel;
}

- (MNDUserAutoTenderRank *)userAutoTenderInfo {
    if (!_userAutoTenderInfo) {
        _userAutoTenderInfo = [MNDUserAutoTenderRank new];
    }
    
    return _userAutoTenderInfo;
}

- (MNDUserAssetModel *)userAssetInfo {
    if (!_userAssetInfo) {
        _userAssetInfo = [MNDUserAssetModel new];
    }
    
    return _userAssetInfo;
}

- (MNDUserMonthProfitModel *)userMonthProfitInfo {
    if (!_userMonthProfitInfo) {
        _userMonthProfitInfo = [MNDUserMonthProfitModel new];
    }
    
    return _userMonthProfitInfo;
}

- (UIView *)depositHeaderView {
    if (!_depositHeaderView) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 35)];
        headerView.backgroundColor = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:239/255.0 alpha:1.0];
        
        UIImage *iconImage = [UIImage imageNamed:@"deposit_note_icon"];
        UIImageView *noteIcon = [[UIImageView alloc] initWithImage:iconImage];
        [headerView addSubview:noteIcon];
        
        [noteIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(headerView).offset(16.0);
            make.centerY.equalTo(headerView);
            make.width.mas_equalTo(iconImage.size.width);
        }];
        
        self.horizontalMarquee = [[JhtHorizontalMarquee alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 32 - 40, 35) withSingleScrollDuration:8.0];
        
        [headerView addSubview:self.horizontalMarquee];
        
        [self.horizontalMarquee mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(noteIcon.mas_trailing).offset(8);
            make.top.equalTo(headerView);
            make.bottom.equalTo(headerView);
        }];
        
        self.horizontalMarquee.text = [NSString stringWithFormat:@"%@     ", self.depositResponse.msg[@"error"]];
        self.horizontalMarquee.font = [UIFont systemFontOfSize:14.0];
        self.horizontalMarquee.textColor = [UIColor colorWithRed:255/255.0 green:176/255.0 blue:107/255.0 alpha:1.0];
        
        [self.horizontalMarquee marqueeOfSettingWithState:MarqueeStart_H];
        
        UIImage *buttonImage = [UIImage imageNamed:@"finance_ntice"];
        UIButton *arrowButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [arrowButton setImage:buttonImage forState:UIControlStateNormal];
        [headerView addSubview:arrowButton];
        
        [arrowButton addTarget:self action:@selector(depositButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [arrowButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(headerView).offset(-16.0);
            make.centerY.equalTo(headerView);
            make.width.mas_equalTo(buttonImage.size.width);
        }];
        
        UIView *gapLine = [[UIView alloc] initWithFrame:CGRectMake(6, 0, 1, 13)];
        gapLine.backgroundColor = [UIColor colorWithRed:255/255.0 green:176/255.0 blue:107/255.0 alpha:1.0];
        [headerView addSubview:gapLine];
        
        [gapLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(arrowButton.mas_leading).offset(-12.0);
            make.width.mas_equalTo(1.0);
            make.top.equalTo(headerView).offset(6.0);
            make.bottom.equalTo(headerView).offset(-6.0);
            make.leading.equalTo(self.horizontalMarquee.mas_trailing).offset(8.0);
        }];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [headerView addSubview:button];
        
        [button addTarget:self action:@selector(depositButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(headerView);
        }];
        
        _depositHeaderView = headerView;
    }
    
    return _depositHeaderView;
}

#pragma mark - 微信绑定
- (void)bindWechat {
    [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeWechat
                                   onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                       NSLog(@"user = %@",user);
                                       //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
                                       //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
                                       [NetworkProgressHUD showHud];
                                       if (user.uid.length <= 0) {
                                           user.uid = @"";
                                       }
                                       if (user.nickname.length <= 0) {
                                           user.nickname = @"";
                                       }
                                       if (user.icon.length <= 0) {
                                           user.icon = @"";
                                       }
                                       
                                       
                                       NSDictionary *params = @{
                                                                @"unionid":user.credential.rawData[@"unionid"],
                                                                @"open_id": user.credential.rawData[@"openid"],
                                                                @"open_name": user.nickname,
                                                                @"open_img": user.icon,
                                                                @"open_sex": user.gender == 0 ? @(-1):@(1),
                                                                @"open_type": @"1",
                                                                @"source": @"app"
                                                                };
                                       kdeclare_weakself;
                                       //开始登录
                                       [APIManager sendRequestWithURL:API_WECHAT_LOGIN parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
                                           [NetworkProgressHUD hideHud];
                                           if (responseModel.status == ResponseSuccess) {
                                               NSString *str = responseModel.data[@"is_bind"];
                                               
                                               if (str.integerValue == -1) {//未绑定
                                                   [weakSelf goBindWechat:(SSDKUser *)user];
                                               }else {//已绑定
                                                   
                                                    [NetworkProgressHUD showHudMsg:@"该微信号已绑定其他账户"];
                                               }

                                               NSLog(@"responseModel = %@",responseModel);
                                           }else {
                                               [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                                           }
                                       } onFailure:^(NSError *error) {
                                           [NetworkProgressHUD showHudNetworkError:error];
                                       }];
                                       associateHandler (user.uid, user, user);
                                       NSLog(@"dd%@",user.rawData);
                                       NSLog(@"dd%@",user.credential);
                                       
                                   }
                                onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                    
                                    if (state == SSDKResponseStateSuccess)
                                    {
                                        
                                    }
                                    
                                }];
    
}

//绑定微信
- (void)goBindWechat:(SSDKUser *)user {
    MNDBindWechatTableViewController *bindVC = [UIStoryboard viewControllerWithIdentifier:@"MNDBindWechatTableViewController"];
    bindVC.isUserCenterEnter = YES;
    bindVC.userPhone = self.userModel.userPhone;
    bindVC.user = user;
    [self.navigationController pushViewController:bindVC animated:YES];
}


@end
